<!--
  智慧社区管理系统 - 支付表单对话框组件
  @author Wu.Liang
  @date 2025-06-26
  @version 3.0 - 根据系统设计调整方案重构，统一支付接口
-->
<template>
  <el-dialog
    v-model="dialogVisible"
    title="新建支付订单"
    width="600px"
    :close-on-click-modal="false"
    @close="handleClose"
  >
    <el-form
      ref="formRef"
      :model="form"
      :rules="rules"
      label-width="120px"
      @submit.prevent
    >
      <el-form-item label="用户" prop="userId">
        <el-select
          v-model="form.userId"
          placeholder="请选择用户"
          style="width: 100%"
          filterable
          remote
          :remote-method="searchUsers"
          :loading="userLoading"
        >
          <el-option
            v-for="user in userList"
            :key="user.id"
            :label="user.name"
            :value="user.id"
          >
            <span>{{ user.name }}</span>
            <span style="float: right; color: #8492a6; font-size: 13px">
              {{ user.phone }}
            </span>
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="社区" prop="communityId">
        <el-select
          v-model="form.communityId"
          placeholder="请选择社区"
          style="width: 100%"
          @change="handleCommunityChange"
        >
          <el-option
            v-for="community in communityList"
            :key="community.id"
            :label="community.name"
            :value="community.id"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="支付金额" prop="amount">
        <el-input-number
          v-model="form.amount"
          :min="0.01"
          :max="999999.99"
          :precision="2"
          :step="0.01"
          style="width: 100%"
          placeholder="请输入支付金额"
        />
      </el-form-item>

      <el-form-item label="支付方式" prop="paymentMethod">
        <el-select
          v-model="form.paymentMethod"
          placeholder="请选择支付方式"
          style="width: 100%"
        >
          <el-option label="微信支付" :value="1" />
          <el-option label="支付宝" :value="2" />
          <el-option label="银行卡" :value="3" />
          <el-option label="现金" :value="4" />
        </el-select>
      </el-form-item>

      <el-form-item label="业务类型" prop="businessType">
        <el-select
          v-model="form.businessType"
          placeholder="请选择业务类型"
          style="width: 100%"
          @change="handleBusinessTypeChange"
        >
          <el-option label="物业费" :value="1" />
          <el-option label="停车费" :value="2" />
          <el-option label="水电费" :value="3" />
          <el-option label="其他" :value="4" />
        </el-select>
      </el-form-item>

      <el-form-item label="业务订单" prop="businessOrderId">
        <el-select
          v-model="form.businessOrderId"
          placeholder="请选择业务订单"
          style="width: 100%"
          filterable
          :loading="orderLoading"
          :disabled="!form.businessType"
        >
          <el-option
            v-for="order in businessOrderList"
            :key="order.id"
            :label="order.orderNo"
            :value="order.id"
          >
            <span>{{ order.orderNo }}</span>
            <span style="float: right; color: #8492a6; font-size: 13px">
              ¥{{ order.amount }}
            </span>
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="描述" prop="description">
        <el-input
          v-model="form.description"
          type="textarea"
          :rows="3"
          placeholder="请输入支付描述"
          maxlength="200"
          show-word-limit
        />
      </el-form-item>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="handleConfirm" :loading="loading">
          确认创建
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, watch, computed } from 'vue'
import { ElMessage } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import type { CreatePaymentParams } from '../types/payment'
import { commonApi } from '@/api/property'

// 作者: Wu.Liang

// Props
interface Props {
  modelValue: boolean
  loading?: boolean
}

const props = withDefaults(defineProps<Props>(), {
  loading: false
})

// Emits
const emit = defineEmits<{
  'update:modelValue': [value: boolean]
  'confirm': [data: CreatePaymentParams]
}>()

// 响应式数据
const formRef = ref<FormInstance>()
const userLoading = ref(false)
const orderLoading = ref(false)

// 表单数据
const form = reactive<CreatePaymentParams>({
  userId: 0,
  communityId: 0,
  amount: 0,
  paymentMethod: 1,
  businessType: 1,
  businessOrderId: 0,
  description: ''
})

// 表单验证规则
const rules: FormRules = {
  userId: [
    { required: true, message: '请选择用户', trigger: 'change' }
  ],
  communityId: [
    { required: true, message: '请选择社区', trigger: 'change' }
  ],
  amount: [
    { required: true, message: '请输入支付金额', trigger: 'blur' },
    { type: 'number', min: 0.01, message: '支付金额必须大于0', trigger: 'blur' }
  ],
  paymentMethod: [
    { required: true, message: '请选择支付方式', trigger: 'change' }
  ],
  businessType: [
    { required: true, message: '请选择业务类型', trigger: 'change' }
  ],
  businessOrderId: [
    { required: true, message: '请选择业务订单', trigger: 'change' }
  ]
}

// 下拉选项数据
const userList = ref<any[]>([])
const communityList = ref<any[]>([])
const businessOrderList = ref<any[]>([])

// 计算属性
const dialogVisible = computed({
  get: () => props.modelValue,
  set: (value) => emit('update:modelValue', value)
})

// 监听器
watch(() => props.modelValue, (newVal) => {
  if (newVal) {
    resetForm()
    loadCommunityList()
  }
})

// 方法
const resetForm = () => {
  Object.assign(form, {
    userId: 0,
    communityId: 0,
    amount: 0,
    paymentMethod: 1,
    businessType: 1,
    businessOrderId: 0,
    description: ''
  })
  formRef.value?.clearValidate()
}

const loadCommunityList = async () => {
  try {
    const response = await commonApi.getCommunityList()
    if (response.data && response.code === 200) {
      communityList.value = response.data
    }
  } catch (error) {
    console.error('加载社区列表失败:', error)
  }
}

const searchUsers = async (query: string) => {
  if (query.length < 2) return
  
  try {
    userLoading.value = true
    // 这里需要后端提供用户搜索接口
    // const response = await userApi.searchUsers({ keyword: query })
    // if (response.data && response.code === 200) {
    //   userList.value = response.data
    // }
  } catch (error) {
    console.error('搜索用户失败:', error)
  } finally {
    userLoading.value = false
  }
}

const handleCommunityChange = () => {
  form.businessOrderId = 0
  businessOrderList.value = []
  if (form.communityId && form.businessType) {
    loadBusinessOrders()
  }
}

const handleBusinessTypeChange = () => {
  form.businessOrderId = 0
  businessOrderList.value = []
  if (form.communityId && form.businessType) {
    loadBusinessOrders()
  }
}

const loadBusinessOrders = async () => {
  if (!form.communityId || !form.businessType) return
  
  try {
    orderLoading.value = true
    // 这里需要后端提供业务订单查询接口
    // const response = await businessApi.getBusinessOrders({
    //   communityId: form.communityId,
    //   businessType: form.businessType,
    //   status: 'unpaid'
    // })
    // if (response.data && response.code === 200) {
    //   businessOrderList.value = response.data
    // }
  } catch (error) {
    console.error('加载业务订单失败:', error)
  } finally {
    orderLoading.value = false
  }
}

const handleClose = () => {
  dialogVisible.value = false
}

const handleConfirm = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    emit('confirm', { ...form })
  } catch (error) {
    console.error('表单验证失败:', error)
  }
}
</script>

<style scoped>
.dialog-footer {
  text-align: right;
}
</style> 